import axios from "axios";
import { db } from "@/storage";
import router from "@/router";
import { appConfig, settingConfig } from "@/config";

class MyRequestAxios {
    constructor(config) {
        this.defaultConfig = config;
    }

    static errorMapCode;
    static tokenConfig;

    static useTokenConfig(token) {
        MyRequestAxios.tokenConfig = token;
    }

    static useErrorMapCode(mapCode) {
        MyRequestAxios.errorMapCode = mapCode;
    }

    static handlerError(ctx) {
        try {
            const error = ctx.response;
            const failHandler = this.failCodeMap.get(error.status);
            if (failHandler) {
                error.message = failHandler.msg;
                if (typeof failHandler.handler === "function") {
                    return failHandler.handler(error && error.data);
                }
            }
            return Promise.reject(error && error.data);
        } catch {
            const error = ctx.response;
            return Promise.reject(error && error.data);
        }
    }

    static setToken(config) {
        const { key, value } = this.tokenConfig;
        const token = db.get('token');
        const tokenKeys = {};
        if (key) {
            tokenKeys[key] = value.split(" ")[0] + " " + token;
        }
        let _header = {};
        if (token) {
            _header = {
                ..._header,
                ...tokenKeys,
            };
        }

        // // 查询是否超时
        // const time = db.get("expires");
        // if (new Date().getTime() - time > appConfig.token?.expires) {
        //     return router.push({
        //         name: settingConfig.loginName,
        //     });
        // }
        return {
            ...config,
            headers: { ...config.headers, ..._header },
        };
    }

    interceptors(instance) {
        instance.interceptors.request.use(
            (config) => {
                return MyRequestAxios.setToken(config);
            },
            (error) => {
                return Promise.reject(error);
            }
        );
        instance.interceptors.response.use(
            function (response) {
                // 2xx 范围内的状态码都会触发该函数。
                // 对响应数据做点什么
                return response;
            },
            function (error) {
                // 超出 2xx 范围的状态码都会触发该函数。
                // 对响应错误做点什么
                return (
                    MyRequestAxios.handlerError &&
                    MyRequestAxios.handlerError(error)
                );
            }
        );
    }

    request(options = {}) {
        const instance = axios.create();
        const { url } = options;
        if (!url) return console.error("缺失url");
        this.interceptors(instance);
        return instance.request({ ...this.defaultConfig, ...options });
    }
}

export default MyRequestAxios;
